import { Select, Space } from 'antd';
import type { FC } from 'react';
import { useState } from 'react';
import { useModel } from 'umi';

type TProps = {
  value?: any;
  width?: string;
  format?: string;
  onChange: TAnyFunction;
};

const CommonSearchCitySelect: FC<TProps> = (props) => {
  const { value, onChange, width = 140 } = props;
  const { initialState } = useModel('@@initialState');
  const { districtMap } = initialState || {};
  const provinceData = ((districtMap || [])[0] || {}).children || [];
  const [provinceMap] = useState<TCityApi.TCityItem[]>(provinceData);
  const [cityMap, setCityMap] = useState<TCityApi.TCityItem[]>([]);
  const [areaMap, setAreaMap] = useState<TCityApi.TCityItem[]>([]);
  const [currentProvince, setCurrentProvince] = useState<string | null>(value?.province || null);
  const [currentCity, setCurrentCity] = useState<string | null>(value?.city || null);
  const [currentArea, setCurrentArea] = useState<string | null>(value?.area || null);

  const handleProvinceChange = (val: string) => {
    const retCity = (provinceMap.find((item) => item.id === val) || {}).children || [];
    setCityMap(retCity);
    setCurrentProvince(val);
    setCurrentArea(null);
    setCurrentCity(null);
    onChange({
      province: val,
      city: null,
      area: null,
    });
  };

  const handleCityChange = (val: string) => {
    const retArea = (cityMap.find((item) => item.id === val) || {}).children || [];
    setAreaMap(retArea);
    setCurrentCity(val);
    setCurrentArea(null);
    onChange({
      province: currentProvince,
      city: val,
      area: null,
    });
  };

  const handleAreaChange = (val: string) => {
    setCurrentArea(val);
    onChange({
      province: currentProvince,
      city: currentCity,
      area: val,
    });
  };

  return (
    <Space size={8}>
      <span>省:</span>
      <Select
        className="mr-8"
        value={currentProvince}
        style={{ width: `${width}px` }}
        onChange={handleProvinceChange}
        placeholder="省"
      >
        {provinceMap.map((item) => (
          <Select.Option key={item.id} value={item.id}>
            {item.name}
          </Select.Option>
        ))}
      </Select>
      <span>市：</span>
      <Select
        className="mr-8"
        value={currentCity}
        style={{ width: `${width}px` }}
        onChange={handleCityChange}
        placeholder="市"
      >
        {cityMap.map((item) => (
          <Select.Option key={item.id} value={item.id}>
            {item.name}
          </Select.Option>
        ))}
      </Select>
      <span>区：</span>
      <Select
        value={currentArea}
        style={{ width: `${width}px` }}
        onChange={handleAreaChange}
        placeholder="区"
      >
        {areaMap.map((item) => (
          <Select.Option key={item.id} value={item.id}>
            {item.name}
          </Select.Option>
        ))}
      </Select>
    </Space>
  );
};

export default CommonSearchCitySelect;
